﻿using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

using System.Net.Mail;

/// <summary>
/// Oct-27-2008 Eun Leem @ WSU
///     This class contains methods that are used frequently in ILE.
///     Methods are mainly about recording or reporting errors.
/// </summary>
public class ILE_Global
{
    protected ILE_Config ileConfig = new ILE_Config();
    protected Log_ErrorBLL logErrorLogic = new Log_ErrorBLL();

    public bool SendEmail(MailAddressCollection Receivers, string Sender, string Subject, string Body)
    {
        MailMessage newMail = new MailMessage();

        try
        {
            MailAddress sender = new MailAddress(Sender);

            newMail.From = sender;
            newMail.Sender = sender;
            newMail.Subject = Subject;
            newMail.Body = Body;
            newMail.IsBodyHtml = true;

            foreach (MailAddress receiver in Receivers)
            {
                newMail.To.Add(receiver);
                SmtpClient smtp = ileConfig.getSMTP();
                smtp.Send(newMail);
                newMail.To.Clear();
            }

            return true;
        }
        catch
        {
            return false;
        }
    }

    public string Validated(string data)
    {
        Regex objRegex = new Regex("[^0-9a-zA-Z %\"\"<>&#$()':;\\/=.,!@?_+-]");
        if (data != null)
        {
            data = objRegex.Replace(data, "");
            data = data.Replace("$", "$");
            data = data.Replace("--", "");
            data = data.Replace("@@", "");
            data = data.Replace("/*", "");
            data = data.Replace("*/", "");
            data = data.Replace("xp_", "");
            data = data.Replace("<script", "");
            data = data.Replace("/script>", "");
            data = data.Replace("<%", "");
            data = data.Replace("%>", "");
            data = data.Replace("<link", "");
            data = data.Replace("/link>", "");
            data = data.Replace("<style", "");
            data = data.Replace("/style>", "");
            data = data.Replace("<!", "");
            data = data.Replace("-->", "");
            data = data.Replace("<--", "");
            data = data.Replace("runat", "");
            data = data.Replace("EXEC", "");
            return data;
        }
        return data;
    }

    public string GetStandardNameByStandardID(int StandardID)
    {
        if (StandardID >= 1 && StandardID <= 4)
        {
            StandardsBLL standardsLogic = new StandardsBLL();
            return standardsLogic.GetStandardByID(StandardID).Standard.ToString();
        }
        else
        {
            return "Invalid StandardID";
        }
    }

    #region Record Error
    public void RecordError(string ErrorCode, Exception ex, int Severity)
    {
        if (ex is HttpUnhandledException)
        {
            ex = ex.InnerException;
        }

        int UserID = 0;

        try
        {
            UserID = Convert.ToInt32(HttpContext.Current.Session["UserID"]);
        }
        catch
        {
            UserID = 2;
        }

        string ErrorMessage = "<h3>Error Message</h3><div style='margin-left: 20px;'>" + ex.Message.ToString() + "</div><br />";
        ErrorMessage += "<h3>Error Source</h3><div style='margin-left: 20px;'>" + ex.Source.ToString() + "</div><br />";
        ErrorMessage += "<h3>Error Target Site</h3><div style='margin-left: 20px;'>" + ex.TargetSite.ToString() + "</div><br />";
        ErrorMessage += "<h3>Error Stack Trace</h3><div style='margin-left: 20px;'>" + ex.StackTrace.ToString() + "</div><br />";
        
        string OS = String.Empty;
        try
        {
            OS = HttpContext.Current.Request.Browser.Platform.ToString();
        }
        catch
        {
            OS = "Unknown";
        }

        string WebBrowser = String.Empty;
        try
        {
            WebBrowser = HttpContext.Current.Request.Browser.Browser.ToString() + " " + HttpContext.Current.Request.Browser.Version.ToString();
        }
        catch
        {
            WebBrowser = "Unknown";
        }

        try
        {
            logErrorLogic.InsertLog_Error(UserID, ErrorCode, ErrorMessage, OS, WebBrowser, Severity);
        }
        catch
        {
            if (ileConfig.getIsErrorReportToEmailEnabled() && Severity >= 4)
            {
                string subject = "[ILE ERROR] Recording Error has Failed.";
                string body = "Time Stamp: " + DateTime.Now.ToString("f").ToString() +
                            "<br /><br />RecordError function in ILE_Global page has failed to record the error." +
                            "<br /><br />Error Message : " + ErrorMessage.ToString() +
                            "<br /><br />Error URL : " + HttpContext.Current.Request.Url.PathAndQuery.ToString();
                ReportError(subject, body);
            }
        }


        if (ileConfig.getIsErrorReportToEmailEnabled() && Severity >= 4)
        {
            string subject = "[ILE ERROR] " + ErrorCode;
            string body = "Time Stamp: " + DateTime.Now.ToLongTimeString();
            try
            {
                body += "<br /><br /><h3>User Information</h3><div style='margin-left: 20px;'>" +
                        "Username: " + HttpContext.Current.User.Identity.Name.ToString() + "</div><br />";
            }
            catch
            {
                body += "<br /><br /><h3>User Information</h3><div style='margin-left: 20px;'>" +
                    "No User Info</div><br />";
            }

            body += "<h3>Operating System:</h3>" + OS + "<br /><br />" + "<h3>Web Browser:</h3>" + WebBrowser;

            body += "<br /><br /><h3>Error Detail:</h3>" + ErrorMessage + "<br /><br />Error Source: " + ex.TargetSite.Name;

            ReportError(subject, body);
        }
    }

    public void RecordError(string ErrorCode, Exception ex, string ErrorDetails, int Severity)
    {

        int userID = 0;
        try
        {
            userID = Convert.ToInt32(HttpContext.Current.Session["UserID"]);
        }
        catch
        {
            userID = 1;
        }



        string errorMessage = "<h3>Error Message</h3><div style='margin-left: 20px;'>" + ex.Message.ToString() + "</div><br />";
        errorMessage += "<h3>Error Source</h3><div style='margin-left: 20px;'>" + ex.Source.ToString() + "</div><br />";
        errorMessage += "<h3>Error Target Site</h3><div style='margin-left: 20px;'>" + ex.TargetSite.ToString() + "</div><br />";
        errorMessage += "<h3>Error Stack Trace</h3><div style='margin-left: 20px;'>" + ex.StackTrace.ToString() + "</div><br />";

        string OS = String.Empty;
        try
        {
            OS = HttpContext.Current.Request.Browser.Platform.ToString();
        }
        catch
        {
            OS = "Unknown";
        }

        string WebBrowser = String.Empty;
        try
        {
            WebBrowser = HttpContext.Current.Request.Browser.Browser.ToString() + " " + HttpContext.Current.Request.Browser.Version.ToString();
        }
        catch
        {
            WebBrowser = "Unknown";
        }

        try
        {
            logErrorLogic.InsertLog_Error(userID, ErrorCode, errorMessage, OS, WebBrowser, Severity);
        }
        catch
        {
            if (ileConfig.getIsErrorReportToEmailEnabled() && Severity >= 4)
            {
                string subject = "[ILE ERROR] Recording Error has Failed.";
                string body = "Time Stamp: " + DateTime.Now.ToString("f").ToString() +
                            "<br /><br />RecordError function in ILE_Global page has failed to record the error." +
                            "<br /><br />Error Message : " + errorMessage.ToString() +
                            "<br /><br />Error URL : " + HttpContext.Current.Request.Url.PathAndQuery.ToString();
                ReportError(subject, body);
            }
        }

        if (ileConfig.getIsErrorReportToEmailEnabled() && Severity >= 4)
        {
            string subject = "ILE Error: " + ErrorCode;
            string body = "Time Stamp: " + DateTime.Now.ToLongTimeString();
            try
            {
                body += "<br /><br /><b>User Information</b><br />" +
                        "Username: " + HttpContext.Current.User.Identity.Name.ToString() + "<br /><br />";
            }
            catch
            {
            }

            try
            {
                body +=
                "Operating System: " + HttpContext.Current.Request.Browser.Platform.ToString() +"<br /><br />" +
                "Web Browser: " + HttpContext.Current.Request.Browser.Browser.ToString() + " " +
                                  HttpContext.Current.Request.Browser.Version.ToString();
            }
            catch
            {
            }

            body += "<br /><br />Error Message:<br />" + errorMessage + "<br /><br />Error Details:<br />" + ErrorDetails + "<br /><br />Error URL:<br />" + HttpContext.Current.Request.Url.PathAndQuery.ToString();
            ReportError(subject, body);
        }
    }

    public void RecordError(string ErrorCode, string ErrorDetails, int Severity)
    {
        int userID = 0;
        try
        {
            userID = Convert.ToInt32(HttpContext.Current.Session["UserID"]);
        }
        catch
        {
            userID = 1;
        }

        string errorMessage = "Error Details:<br />" + ErrorDetails + "<br />URL: " + HttpContext.Current.Request.Url.PathAndQuery.ToString();
        string OS = String.Empty;
        try
        {
            OS = HttpContext.Current.Request.Browser.Platform.ToString();
        }
        catch
        {
            OS = "Unknown";
        }

        string WebBrowser = String.Empty;
        try
        {
            WebBrowser = HttpContext.Current.Request.Browser.Browser.ToString() + " " + HttpContext.Current.Request.Browser.Version.ToString();
        }
        catch
        {
            WebBrowser = "Unknown";
        }

        try
        {
            logErrorLogic.InsertLog_Error(userID, ErrorCode, errorMessage, OS, WebBrowser, Severity);
        }
        catch
        {
            if (ileConfig.getIsErrorReportToEmailEnabled() && Severity >= 4)
            {
                string subject = "[ILE ERROR] Recording Error has Failed.";
                string body = "Time Stamp: " + DateTime.Now.ToString("f").ToString() +
                            "<br /><br />RecordError function in ILE_Global page has failed to record the error." +
                            "<br /><br />Error Message : " + ErrorDetails.ToString() +
                            "<br /><br />Error URL : " + HttpContext.Current.Request.Url.PathAndQuery.ToString();
                ReportError(subject, body);
            }
        }

        if (ileConfig.getIsErrorReportToEmailEnabled() && Severity >= 4)
        {
            string subject = "[ILE Error] " + ErrorCode;
            if (ErrorCode.Contains("Global.asax"))
            {
                subject = "[*ILE Error] " + ErrorCode;
            }

            string body = "<br /><br />Error Details:<br />" + ErrorDetails;
            try
            {
                body +=
                "<br /><br />Operating System: " + HttpContext.Current.Request.Browser.Platform.ToString() + "<br /><br />" +
                "Web Browser: " + HttpContext.Current.Request.Browser.Browser.ToString() + " " +
                                  HttpContext.Current.Request.Browser.Version.ToString();
            }
            catch
            {
                body += "<br /><br /><b>User System Environment information is not available</b><br />";
            }

            ReportError(subject, body);
        }
    }

    public void RecordError(string ErrorCode, Exception ex, int Severity, HttpBrowserCapabilities Browser)
    {
        if (ex is HttpUnhandledException)
        {
            ex = ex.InnerException;
        }

        int UserID = 0;

        try
        {
            UserID = Convert.ToInt32(HttpContext.Current.Session["UserID"]);
        }
        catch
        {
            UserID = 2;
        }

        string ErrorMessage = "<h3>Error Message</h3><div style='margin-left: 20px;'>" + ex.Message.ToString() + "</div><br />";
        ErrorMessage += "<h3>Error Source</h3><div style='margin-left: 20px;'>" + ex.Source.ToString() + "</div><br />";
        ErrorMessage += "<h3>Error Target Site</h3><div style='margin-left: 20px;'>" + ex.TargetSite.ToString() + "</div><br />";
        ErrorMessage += "<h3>Error Stack Trace</h3><div style='margin-left: 20px;'>" + ex.StackTrace.ToString() + "</div><br />";

        string OS = String.Empty;
        try
        {
            OS = Browser.Platform.ToString();
        }
        catch
        {
            OS = "Unknown";
        }

        string WebBrowser = String.Empty;
        try
        {
            WebBrowser = Browser.Browser.ToString() + " " + Browser.Version.ToString();
        }
        catch
        {
            WebBrowser = "Unknown";
        }

        try
        {
            logErrorLogic.InsertLog_Error(UserID, ErrorCode, ErrorMessage, OS, WebBrowser, Severity);
        }
        catch
        {
            if (ileConfig.getIsErrorReportToEmailEnabled() && Severity >= 4)
            {
                string subject = "[ILE ERROR] Recording Error has Failed.";
                string body = "Time Stamp: " + DateTime.Now.ToString("f").ToString() +
                            "<br /><br />RecordError function in ILE_Global page has failed to record the error." +
                            "<br /><br />Error Message : " + ErrorMessage.ToString() +
                            "<br /><br />Error URL : " + HttpContext.Current.Request.Url.PathAndQuery.ToString();
                ReportError(subject, body);
            }
        }

        if (ileConfig.getIsErrorReportToEmailEnabled() && Severity >= 4)
        {
            string subject = "[ILE ERROR] " + ErrorCode;
            string body = "Time Stamp: " + DateTime.Now.ToLongTimeString();
            try
            {
                body += "<br /><br /><h3>User Information</h3><div style='margin-left: 20px;'>" +
                        "Username: " + HttpContext.Current.User.Identity.Name.ToString() + "</div><br />";
            }
            catch
            {
                body += "<br /><br /><h3>User Information</h3><div style='margin-left: 20px;'>" +
                    "No User Info</div><br />";
            }

            body += "<h3>Operating System:</h3>" + OS + "<br /><br />" + "<h3>Web Browser:</h3>" + WebBrowser;

            body += "<br /><br /><h3>Error Detail:</h3>" + ErrorMessage + "<br /><br />Error Source: " + ex.TargetSite.Name;

            ReportError(subject, body);
        }
    }

    public void RecordError(string ErrorCode, Exception ex, string ErrorDetails, int Severity, HttpBrowserCapabilities Browser)
    {

        int userID = 0;
        try
        {
            userID = Convert.ToInt32(HttpContext.Current.Session["UserID"]);
        }
        catch
        {
            userID = 1;
        }



        string errorMessage = "<h3>Error Message</h3><div style='margin-left: 20px;'>" + ex.Message.ToString() + "</div><br />";
        errorMessage += "<h3>Error Source</h3><div style='margin-left: 20px;'>" + ex.Source.ToString() + "</div><br />";
        errorMessage += "<h3>Error Target Site</h3><div style='margin-left: 20px;'>" + ex.TargetSite.ToString() + "</div><br />";
        errorMessage += "<h3>Error Stack Trace</h3><div style='margin-left: 20px;'>" + ex.StackTrace.ToString() + "</div><br />";

        string OS = String.Empty;
        try
        {
            OS = Browser.Platform.ToString();
        }
        catch
        {
            OS = "Unknown";
        }

        string WebBrowser = String.Empty;
        try
        {
            WebBrowser = Browser.Browser.ToString() + " " + Browser.Version.ToString();
        }
        catch
        {
            WebBrowser = "Unknown";
        }

        try
        {
            logErrorLogic.InsertLog_Error(userID, ErrorCode, errorMessage, OS, WebBrowser, Severity);
        }
        catch
        {
            if (ileConfig.getIsErrorReportToEmailEnabled() && Severity >= 4)
            {
                string subject = "[ILE ERROR] Recording Error has Failed.";
                string body = "Time Stamp: " + DateTime.Now.ToString("f").ToString() +
                            "<br /><br />RecordError function in ILE_Global page has failed to record the error." +
                            "<br /><br />Error Message : " + errorMessage.ToString() +
                            "<br /><br />Error URL : " + HttpContext.Current.Request.Url.PathAndQuery.ToString();
                ReportError(subject, body);
            }
        }

        if (ileConfig.getIsErrorReportToEmailEnabled() && Severity >= 4)
        {
            string subject = "ILE Error: " + ErrorCode;
            string body = "Time Stamp: " + DateTime.Now.ToLongTimeString();
            try
            {
                body += "<br /><br /><b>User Information</b><br />" +
                        "Username: " + HttpContext.Current.User.Identity.Name.ToString() + "<br /><br />";
            }
            catch
            {
            }

            try
            {
                body +=
                "Operating System: " + Browser.Platform.ToString() + "<br /><br />" +
                "Web Browser: " + Browser.Browser.ToString() + " " +
                                  Browser.Version.ToString();
            }
            catch
            {
            }

            body += "<br /><br />Error Message:<br />" + errorMessage + "<br /><br />Error Details:<br />" + ErrorDetails + "<br /><br />Error URL:<br />" + HttpContext.Current.Request.Url.PathAndQuery.ToString();
            ReportError(subject, body);
        }
    }

    public void RecordError(string ErrorCode, string ErrorDetails, int Severity, HttpBrowserCapabilities Browser)
    {
        int userID = 0;
        try
        {
            userID = Convert.ToInt32(HttpContext.Current.Session["UserID"]);
        }
        catch
        {
            userID = 1;
        }

        string errorMessage = "Error Details:<br />" + ErrorDetails + "<br />URL: " + HttpContext.Current.Request.Url.PathAndQuery.ToString();
        string OS = String.Empty;
        try
        {
            OS = Browser.Platform.ToString();
        }
        catch
        {
            OS = "Unknown";
        }

        string WebBrowser = String.Empty;
        try
        {
            WebBrowser = Browser.Browser.ToString() + " " + Browser.Version.ToString();
        }
        catch
        {
            WebBrowser = "Unknown";
        }

        try
        {
            logErrorLogic.InsertLog_Error(userID, ErrorCode, errorMessage, OS, WebBrowser, Severity);
        }
        catch
        {
            if (ileConfig.getIsErrorReportToEmailEnabled() && Severity >= 4)
            {
                string subject = "[ILE ERROR] Recording Error has Failed.";
                string body = "Time Stamp: " + DateTime.Now.ToString("f").ToString() +
                            "<br /><br />RecordError function in ILE_Global page has failed to record the error." +
                            "<br /><br />Error Message : " + ErrorDetails.ToString() +
                            "<br /><br />Error URL : " + HttpContext.Current.Request.Url.PathAndQuery.ToString();
                ReportError(subject, body);
            }
        }

        if (ileConfig.getIsErrorReportToEmailEnabled() && Severity >= 4)
        {
            string subject = "[ILE Error] " + ErrorCode;
            if (ErrorCode.Contains("Global.asax"))
            {
                subject = "[*ILE Error] " + ErrorCode;
            }

            string body = "<br /><br />Error Details:<br />" + ErrorDetails;
            try
            {
                body +=
                "<br /><br />Operating System: " + Browser.Platform.ToString() + "<br /><br />" +
                "Web Browser: " + Browser.Browser.ToString() + " " +
                                  Browser.Version.ToString();
            }
            catch
            {
                body += "<br /><br /><b>User System Environment information is not available</b><br />";
            }

            ReportError(subject, body);
        }
    }

    private void ReportError(string Subject, string Body)
    {
        try
        {
            ILE_Global ileGlobal = new ILE_Global();
            ileGlobal.SendEmail(ileConfig.getErrorReportReceivers(), ileConfig.getErrorReportSender(), Subject, Body);
        }
        catch
        {

        }
    }
    #endregion
}
